#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

change=0
while [ "1" = "1" ]
do
	#get the local ip and the broadcast ip
	interface=$(cat /proc/net/dev | awk '{i++; if(i>2){print $1}}' | sed 's/^[\t]*//g' | sed 's/[:]*$//g' | egrep -v "(docker|lo|wlan)")
	local_ip=$(ifconfig $interface |grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:")
	broadcast_ip=$(ifconfig $interface |grep broadcast | awk -F " " '{print $6}')
	if [ -z $local_ip ]
	then
		change=0
	else
		if [ $change -eq 0 ]
		then
			#define the parameter
			username="ubuntu"
			password="root"
			port=22
			input_file="recode"
			cfile="send.c"
			cfile_copy="send-copy.c"
			out_file="send-copy.out"
			server_info="server_info"
			home_path="/home/"$username
			file_path="$home_path/$input_file"
			cfile_path="$home_path/$cfile"
			cfile_copy_path="$home_path/$cfile_copy"
			out_file_path="$home_path/$out_file"
			server_info_path="$home_path/$server_info"

			#get the interface not contain lo
			#interface=$(cat /proc/net/dev | awk '{i++; if(i>2){print $1}}' | sed 's/^[\t]*//g' | sed 's/[:]*$//g' | awk '/[^lo]/')

			#update the send.c with the local_ip and broadcast_ip which have got
			sed -e 's/broadcast_ip/'$broadcast_ip'/g' -e 's/local_ip/'$local_ip'/g' $cfile_path > $cfile_copy_path 

			#use gcc commond to get the send-copy.out and get the server ip
			gcc $cfile_copy_path -o $out_file_path
			$out_file_path > $server_info_path
			server_ip=`cat $server_info_path | awk -F " " '{print $1}'`
			server_username=`cat $server_info_path | awk -F " " '{print $2}'`
			server_pwd=`cat $server_info_path | awk -F " " '{print $3}'`
			server_filepath="/home/"$server_username"/"$local_ip"_"$input_file

			#install the software
			#sudo apt-get install -y  expect

			#input the username, password, port, home_path to the file "recode"
			echo $port >> $file_path
			echo $username  >> $file_path
			echo $password >> $file_path
			echo $home_path >> $file_path

			#use scp comand to send the file "recode" to the server
			expect -c "
			spawn scp -r \"$file_path\" $server_username@$server_ip:$server_filepath
			expect {
			\"*assword\" {set timeout 300; send \"$server_pwd\r\";}
			\"yes/no\" {send \"yes\r\"; exp_continue;}
			}
			expect eof"

		    rm -rf recode send-copy.* server_info
		fi
		change=1
	fi
    sleep 1s
done
